import { createRouter, createWebHashHistory } from "vue-router";
import systemRouter from "./systemRouter";
//系统路由
const routes = systemRouter;

const router = createRouter({
  history: createWebHashHistory(),
  routes: routes,
});

//判断是否已加载过动态/静态路由
var isGetRouter = false;

router.beforeEach(async (to, from, next) => {//to: 即将要进入的目标路由对象 from: 当前正在离开的路由对象
  let token = localStorage.getItem("jm_token");
  if (to.path === "/login") {
    //删除路由(替换当前layout路由)
    router.addRoute(routes[0]);
    //删除路由(404)
    // routes_404_r()
    isGetRouter = false;
    next();
    return false;
  }

  if (routes.findIndex((r) => r.path === to.path) >= 0) {//findIndex找不到返回-1 找到返回索引
    next();
    return false;
  }
  if (!token) {//没有token跳到登陆页面
    next({
      path: "/login",
    });
    return false;
  }
  //加载动态/静态路由
  if (!isGetRouter) {
    let apiMenu = JSON.parse(localStorage.getItem("jm_menu")) || [];
    let menu = apiMenu;
    var menuRouter = filterAsyncRouter(menu);
    menuRouter = flatAsyncRoutes(menuRouter);
    menuRouter.forEach((item) => {
      // console.log("item: ", item);
      router.addRoute("layout", item);//添加到指定父级路由 "layout"
    });
    // routes_404_r = router.addRoute(routes_404);
    if (to.matched.length == 0) {
      router.push(to.fullPath);
    }
    isGetRouter = true;
  }
  next();
});

function filterAsyncRouter(routerMap) {
  const accessedRouters = [];
  routerMap.forEach((item) => {
    item.meta = item.meta ? item.meta : {};
    //MAP转路由对象
    var route = {
      path: item.path,
      name: item.name,
      meta: item.meta,
      redirect: item.redirect,
      children: item.children ? filterAsyncRouter(item.children) : null,
      component: loadComponent(item.component),
    };
    accessedRouters.push(route);
  });
  return accessedRouters;
}
function loadComponent(component) {
  if (component) {
    return () =>
        import(/* webpackChunkName: "[request]" */ `@/views/${component}`);
  }
}
function flatAsyncRoutes(routes, breadcrumb = []) {
  let res = [];
  routes.forEach((route) => {
    const tmp = { ...route };
    if (tmp.children) {
      let childrenBreadcrumb = [...breadcrumb];
      childrenBreadcrumb.push(route);
      let tmpRoute = { ...route };
      tmpRoute.meta.breadcrumb = childrenBreadcrumb;
      delete tmpRoute.children;
      res.push(tmpRoute);
      let childrenRoutes = flatAsyncRoutes(tmp.children, childrenBreadcrumb);
      childrenRoutes.map((item) => {
        res.push(item);
      });
    } else {
      let tmpBreadcrumb = [...breadcrumb];
      tmpBreadcrumb.push(tmp);
      tmp.meta.breadcrumb = tmpBreadcrumb;
      res.push(tmp);
    }
  });
  return res;
}

//入侵追加自定义方法、对象
router.sc_getMenu = () => {
  var apiMenu = JSON.parse(localStorage.getItem("jm_menu")) || [];
  return apiMenu;
};
export default router;

